import DragModal from '@/components/DragModal';
import Header from '@/components/Header';
import Logo from '@/components/Logo';
import { doFetch } from '@/utils/doFetch';
import { formartime } from '@/utils/time';
import {
  LogoutOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  MessageOutlined,
} from '@ant-design/icons';
import { ProChat } from '@ant-design/pro-chat';
import { history, Outlet, useModel, useOutletContext } from '@umijs/max';
import { useInterval } from 'ahooks';
import { DatePicker, Grid, Tooltip, theme, Segmented } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { memo, useRef, useState, useEffect } from 'react';
import GlobalSearch from './components/globalSearch';
import Notice from './components/notice';
import HeaderDropDown from './components/headerdropdown';
import MenuBar from './components/menuBar';
import styles from './index.less';
import Switches from '@/components/Switches/index';
import Weather from '@/components/Weather';
import useCurrentUser from '@/utils/useCurrentUser';

dayjs.locale('zh-cn');
const { useBreakpoint } = Grid;

const Clock = memo(({ currentUser, curpro }) => {
  const { initialState: { range }, setInitialState } = useCurrentUser();
  function setRange(val) {
    setInitialState(s => ({
      ...s,
      range: val
    }))
  }

  const handleSegmentChange = (value) => {
    let startDate, endDate;

    switch (value) {
      case '本周':
        startDate = dayjs().startOf('week');
        endDate = dayjs().endOf('week');
        break;
      case '上周':
        startDate = dayjs().subtract(1, 'week').startOf('week');
        endDate = dayjs().subtract(1, 'week').endOf('week');
        break;
      case '本月':
        startDate = dayjs().startOf('month');
        endDate = dayjs().endOf('month');
        break;
      case '上月':
        startDate = dayjs().subtract(1, 'month').startOf('month');
        endDate = dayjs().subtract(1, 'month').endOf('month');
        break;
      default:
        break;
    }
    setRange([startDate, endDate]);
  };

  return (
    <div className={styles?.hello}>
      <Segmented
        options={['本周', '上周', '本月', '上月']}
        onChange={handleSegmentChange}
      />
      <DatePicker.RangePicker value={range} onChange={setRange} variant='borderless' />

    </div>
  );
});

function LayoutDom() {
  const {
    token: {
      colorBgSecondary,
      colorBgSeven,
      colorText,
      colorPrimary,
      colorleftNav,
      colorBgFourth,
      colorBgThird
    },
  } = theme.useToken();
  const { mode } = useOutletContext();
  const scrollRef = useRef();

  const {
    currentUser,
    initialState: { curpro, unreadJoinOrgInvitationCount },
    getUser,
    updateUser
  } = useCurrentUser();


  const { lg } = useBreakpoint();
  const [collspan, setCollspan] = useState(false);
  const [modal, setModal] = useState({
    open: false,
  });
  const [search, setSearch] = useState({
    open: false,
    value: null,
  });
  //响应式
  useEffect(() => {
    setCollspan(!lg);
  }, [lg]);

  const inputRef = useRef();


  // useEffect(() => {
  //   if (!currentUser?.guide?.firstinfos) {
  //     setModal((s) => ({
  //       ...s,
  //       open: true,
  //       title: '完善信息',
  //     }));
  //   }
  // }, [currentUser?.guide]);

  return (
    <div
      className={styles.homepage}
      id="container"
      style={{ '--bg': colorBgSecondary, '--prcolor': colorPrimary, color: colorText }}
    >
      <Weather></Weather>
      <DragModal
        {...modal}
        onCancel={() => {
          setModal((s) => ({
            ...s,
            open: false,
          }));
        }}
        width={516}
        style={{
          '--backgroundColor': colorBgSeven,
          top: '4%',
        }}
      >
        {modal?.title === '全局搜索' && (
          <GlobalSearch
            value={search.value}
            setSearch={setSearch}
            inputRef={inputRef}
          ></GlobalSearch>
        )}
        {modal?.title === 'ChatGPT' && (
          <div style={{ backgroundColor: colorBgSeven, borderRadius: 4 }}>
            <ProChat
              //displayMode={'docs'}
              style={{
                height: '82vh',
                width: '100%',
              }}
              request={async (messages) => {
                const response = await fetch('/apies/aliyun/getApiResult', {
                  method: 'POST',
                  headers: {
                    Authorization:
                      'Bearer ' + 'sk-5e304f3c097544958802d77fc2c7df82',
                    'Content-Type': 'application/json',
                    token: localStorage.getItem('TOKENES'),
                  },
                  body: JSON.stringify({
                    model: 'qwen-turbo',
                    input: {
                      messages,
                    },
                    parameters: {},
                  }),
                });
                const data = await response.json();
                return new Response(data.output?.text);

                // const response = await fetch('/apies/aliyun/getApiResult', {
                //   method: 'POST',
                //   headers: {
                //     Authorization: 'Bearer ' + 'sk-5e304f3c097544958802d77fc2c7df82',
                //     'Content-Type': 'application/json',
                //     token: localStorage.getItem('TOKENES'),
                //     Accept: 'text/event-stream',
                //   },
                //   body: JSON.stringify({
                //     model: 'qwen-turbo',
                //     input: {
                //       messages,
                //     },
                //     parameters: {
                //       incremental_output: false,
                //     },
                //   }),
                // });
                // console.log('====================================');
                // console.log(response.body);
                // console.log('====================================');

                // const reader = response.body.getReader();
                // const decoder = new TextDecoder('utf-8');
                // const encoder = new TextEncoder();
                // let content = '';

                // const readableStream = new ReadableStream({
                //   async start(controller) {
                //     function push() {
                //       reader
                //         .read()
                //         .then(({ done, value }) => {
                //           if (done) {
                //             controller.close();
                //             return;
                //           }
                //           const chunk = decoder.decode(value, { stream: true });
                //           chunk.split('\n').forEach(async (line) => {
                //             if (line && line.includes('data')) {
                //               console.log('line: ', line.replace(/^data:/, ''));
                //               const chatMessage = JSON.parse(line.replace(/^data:/, ''));
                //               content = chatMessage?.output?.text;
                //             }
                //           });

                //           controller.enqueue(encoder.encode(content));
                //           push();
                //         })
                //         .catch((err) => {
                //           console.error('读取流中的数据时发生错误', err);
                //           controller.error(err);
                //         });
                //     }
                //     push();
                //   },
                // });
                // return new Response(readableStream);
              }}
            />
          </div>
        )}
        {modal?.title === '发布公告' && (
          <Notice></Notice>
        )}
      </DragModal>
      <div className={styles.leftnav} style={{ backgroundColor: colorleftNav, minWidth: collspan ? 60 : 160, transition: "all 0.4s",color:colorBgFourth }}>
        <div>
          <div className={styles.logo} onClick={() => {
            history.push("/welcome/homepage");
          }}>
            <div style={{ width: 40 }} className='center'>
              <Logo></Logo>
            </div>
            {!collspan && 'Tasks'}
          </div>
          <div
            className="columns"
          >
            <MenuBar
              unreadJoinOrgInvitationCount={unreadJoinOrgInvitationCount}
              collspan={collspan}
              setCollspan={setCollspan}
              onSearch={() => {
                setModal((s) => ({
                  ...s,
                  open: true,
                  title: '全局搜索',
                }));
                setTimeout(() => {
                  inputRef?.current?.focus();
                }, 600);
              }}
              onGpt={() => {
                setModal((s) => ({
                  ...s,
                  open: true,
                  title: 'ChatGPT',
                  width: 850,
                }));
              }}
              onTeam={() => {
                setModal((s) => ({
                  ...s,
                  open: true,
                  title: '发布公告',
                  width: 850,
                }));
              }}
            ></MenuBar>
          </div>
        </div>

        <div
          className="columns"
          style={{ justifyContent: 'flex-start', alignItems: 'flex-start', gap: 12, paddingLeft: !collspan ? 12 : 14 }}
        >
          <Tooltip title={collspan ? '展开' : '收起'} placement="right">
            <div
              className="sorts"
              onClick={() => {
                setCollspan(!collspan);
              }}
            >
              {collspan ? (
                <MenuUnfoldOutlined style={{
                  fontSize: 18,

                }} />
              ) : (
                <MenuFoldOutlined style={{
                  fontSize: 18,

                }} />
              )}
            </div>
          </Tooltip>

          <Tooltip title="退出登录" placement="right">
            <div
              className="sorts"
              onClick={() => {
                doFetch({ url: '/system/logout', params: {} }).then(() => {
                  localStorage.removeItem('TOKENES');
                  localStorage.setItem('THEME', currentUser?.theme);
                  history.push('/user/login');
                });
              }}
            >
              <LogoutOutlined style={{ color: '#fff', fontSize: 18 }} />
            </div>
          </Tooltip>
        </div>
      </div>
      <div className={styles.rightnav}>
        <div className={styles.header} >
          <div
            className="centerl"
            style={{ width: 310, color: colorText, gap: 6 }}
          >
            <Clock currentUser={currentUser} curpro={curpro}></Clock>
          </div>
          <div
            style={{
              width: 350,
              display: 'flex',
              justifyContent: 'flex-end',
              alignItems: 'center',
              gap: 12,
              color: colorText,
            }}
          >
            <Switches></Switches>
            <HeaderDropDown>
              <Header
                currentUser={currentUser}
                mode={mode}
                colorPrimary={colorPrimary}
                size={34}
              ></Header>
            </HeaderDropDown>
          </div>
        </div>

        <div className={styles.content} id="containbox" >
          <div style={{ height: '100%', padding: "0px 12px 12px 12px", overflowX: "hidden" }} id='contentbox' className='element' ref={scrollRef}>
            <Outlet context={{ scrollRef }} />
          </div>
        </div>

      </div>
    </div>
  );
}

export default LayoutDom;
